package com.training.jwt;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.training.base.ResponseUtils;
import com.training.base.Result;
import com.training.bean.User;
import com.training.web.repository.WebUserRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private WebUserRepository webUserRepository;
    
    @Autowired
    private ResponseUtils responseUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取令牌
        String token = request.getHeader("Authorization");

        try {
            // 处理 Bearer 前缀
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7); // 去掉 "Bearer " 前缀
            }
            
            // 验证令牌的有效性并获取payload
            DecodedJWT decodedJWT = JWTUtils.getToken(token);
            String userIdStr = decodedJWT.getClaim("id").asString();
            String userType = decodedJWT.getClaim("userType").asString();
            
            // 根据用户类型检查是否被禁用
            if (userIdStr != null && userType != null) {
                int userId = Integer.parseInt(userIdStr);
                
                // 如果是普通用户，检查是否被禁用
                if ("user".equals(userType)) {
                    User user = webUserRepository.findUserById(userId);
                    if (user != null && user.getDisabled()) {
                        // 用户被禁用，返回特定code
                        Result<Object> result = Result.fail(401, "用户已被禁用");
                        writeToResponse(response, result);
                        return false;
                    }
                }
                // 如果是管理员，则不检查禁用状态，直接放行
            }
            
            return true; // 放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            // 无效签名
            Result<Object> result = Result.fail(401, "无效签名!");
            writeToResponse(response, result);
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            // token过期
            Result<Object> result = Result.fail(401, "token过期!");
            writeToResponse(response, result);
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            // token算法不一致
            Result<Object> result = Result.fail(401, "token算法不一致!");
            writeToResponse(response, result);
        } catch (Exception e) {
            e.printStackTrace();
            // token无效
            Result<Object> result = Result.fail(401, "token无效!!");
            writeToResponse(response, result);
        }

        return false; // 不放行请求
    }
    
    private void writeToResponse(HttpServletResponse response, Result<Object> result) throws Exception {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getOutputStream(), result);
    }
}